package cn.iocoder.yudao.module.activity.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.iocoder.yudao.module.activity.entity.ActivityDO;
import cn.iocoder.yudao.module.activity.mapper.ActivityMapper;
import cn.iocoder.yudao.module.activity.service.ActivityService;
import cn.iocoder.yudao.module.activity.vo.ActivityPageReqVO;
import cn.iocoder.yudao.module.activity.vo.ActivitySaveReqVO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.infra.enums.ErrorCodeConstants.ACTIVITY_NOT_EXISTS;

/**
 * 招聘活动 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Override
    public Long create(ActivitySaveReqVO createReqVO) {
        // 插入
        ActivityDO activityDO = BeanUtils.toBean(createReqVO, ActivityDO.class);
        activityMapper.insert(activityDO);
        // 返回
        return activityDO.getId();
    }

    @Override
    public void update(ActivitySaveReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        ActivityDO updateObj = BeanUtils.toBean(updateReqVO, ActivityDO.class);
        activityMapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        activityMapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (activityMapper.selectById(id) == null) {
            throw exception(ACTIVITY_NOT_EXISTS);
        }
    }

    @Override
    public ActivityDO get(Long id) {
        return activityMapper.selectById(id);
    }

    @Override
    public PageResult<ActivityDO> getPage(ActivityPageReqVO pageReqVO) {
        return activityMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ActivityDO> getList(ActivityPageReqVO pageReqVO) {
        LambdaQueryWrapper<ActivityDO> activityDOLambdaQueryWrapper = new LambdaQueryWrapper<ActivityDO>().orderByDesc(ActivityDO::getStartTime);
        if(StrUtil.isNotBlank(pageReqVO.getActivityName())){
            activityDOLambdaQueryWrapper.like(ActivityDO::getActivityName, pageReqVO.getActivityName());
        }
        return activityMapper.selectList(activityDOLambdaQueryWrapper);
    }

}